<template>
  <div class="login-container">
    <!-- 左侧区域 - 大屏显示 -->
    <div class="left-section">
      <div class="logo-wrapper desktop-only">
        <img src="@/assets/logo.png" alt="Logo" class="logo" />
        <span>Rhythmic Soar</span>
      </div>
      <div class="title text-ellipsis">{{ t('login.title') }}</div>
      <div class="subtitle text-ellipsis">{{ t('login.subtitle') }}</div>
    </div>

    <!-- 移动端顶部 Logo -->
    <div class="mobile-header">
      <div class="logo-wrapper">
        <img src="@/assets/logomobile.png" alt="Logo" class="logo" />
      </div>
      <div class="subtitle">{{ t('login.title') }}</div>
    </div>

    <!-- 右侧/主要区域 -->
    <div class="main-section">
      <!-- 右上角语言切换 -->
      <div class="top-right-controls">
        <ThemeSwitch />
        <el-dropdown class="lang-switch" trigger="click" @command="handleLanguageChange">
          <span class="lang-dropdown-link">
            <img
              src="https://lf3-cdn-tos.bytegoofy.com/obj/goofy/system/platform/ngid_fe/1.0.0.113/images/global.svg"
              alt="language"
              class="language-icon"
            />
            {{ locale === 'zh-CN' ? '简体中文' : 'English' }}
            <el-icon class="el-icon--right"><arrow-down /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="zh-CN">
                <span :class="{ active: locale === 'zh-CN' }">简体中文</span>
                <el-icon v-if="locale === 'zh-CN'"><check /></el-icon>
              </el-dropdown-item>
              <el-dropdown-item command="en">
                <span :class="{ active: locale === 'en' }">English</span>
                <el-icon v-if="locale === 'en'"><check /></el-icon>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>

      <!-- 登录表单区域 -->
      <div class="login-form">
        <!-- 步骤1：输入账号 -->
        <template v-if="step === 1">
          <div class="form-title">{{ t('login.inputAccount') }}</div>
          <div class="input-group">
            <div class="input-wrapper">
              <input
                v-model="form.username"
                type="text"
                :placeholder="t('login.placeholder.username')"
                @keyup.enter="handleNext"
              />
              <div class="domain-select-wrapper">
                <el-select
                  v-model="selectedDomain"
                  class="domain-select"
                  popper-class="domain-select-dropdown"
                  :popper-append-to-body="false"
                >
                  <el-option
                    v-for="item in domainList"
                    :key="item.value"
                    :label="item.value"
                    :value="item.value"
                  >
                    <div class="domain-option">
                      <span>{{ item.value }}</span>
                      <el-icon v-if="selectedDomain === item.value"><check /></el-icon>
                    </div>
                  </el-option>
                </el-select>
                <div class="domain-text">
                  {{ selectedDomain }}
                  <el-icon class="select-icon"><arrow-down /></el-icon>
                </div>
              </div>
            </div>
          </div>
          <button 
            class="next-btn"
            :disabled="!form.username"
            @click="handleNext"
          >
            {{ t('login.nextStep') }}
          </button>
          
          <!-- 其他登录方式 -->
          <div class="other-login">
            <div class="divider">
              <span>{{ t('login.otherLogin') }}</span>
            </div>
            <div class="login-methods">
              <el-tooltip content="密钥通行" placement="top">
                <div class="login-icon">
                  <img 
                    src="https://lf3-cdn-tos.bytegoofy.com/obj/goofy/system/platform/ngid_libs/images/sso/passkey.jpeg"
                    alt="密钥通行"
                    class="icon-img"
                  />
                </div>
              </el-tooltip>
              <el-tooltip content="飞书登录" placement="top">
                <div class="login-icon">
                  <img 
                    src="https://lf3-cdn-tos.bytegoofy.com/obj/goofy/system/platform/ngid_libs/images/branding/icon/lark.svg"
                    alt="飞书登录"
                    class="icon-img"
                  />
                </div>
              </el-tooltip>
              <el-tooltip content="Google登录" placement="top">
                <div class="login-icon">
                  <img 
                    src="https://lf3-cdn-tos.bytegoofy.com/obj/goofy/system/platform/ngid_libs/images/branding/icon/google.svg"
                    alt="Google登录"
                    class="icon-img" 
                  />
                </div>
              </el-tooltip>
            </div>
          </div>
        </template>

        <!-- 步骤2：输入密码 -->
        <template v-if="step === 2">
          <!-- 返回按钮 -->
          <div class="back-btn" @click="handleChangeAccount">
            <el-icon><arrow-left /></el-icon>
            {{ t('login.back') }}
          </div>

          <!-- 标题和账号显示 -->
          <div class="password-title">{{ t('login.inputPassword') }}</div>
          <div class="account-info">{{ form.username }}</div>

          <!-- 密码输入框 -->
          <div class="input-group">
            <div class="input-wrapper">
              <input
                v-model="form.password"
                type="password"
                :placeholder="t('login.placeholder.password')"
                @keyup.enter="handleLogin"
              />
              <el-icon class="password-icon"><view /></el-icon>
            </div>
          </div>

          <!-- 登录按钮 -->
          <button 
            class="next-btn"
            :disabled="!form.password || loading"
            :loading="loading"
            @click="handleLogin"
          >
            {{ t('login.login') }}
          </button>

          <!-- 忘记密码链接 -->
          <div class="forgot-password">
            <a href="#">{{ t('login.forgotPassword') }}</a>
          </div>
        </template>
      </div>


      <!-- 底部版权信息 -->
      <div class="copyright">
        <p>{{ t('login.copyright') }} <img src="https://lf3-cdn-tos.bytegoofy.com/obj/goofy/system/platform/ngid_fe/1.0.0.113/images/icp.png" alt="ICP备案" style="width: 14px; height: 14px; margin-right: 4px; vertical-align: middle;" /> {{ t('login.beian') }}</p>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ArrowDown, Check, ArrowLeft } from '@element-plus/icons-vue'
import { ElMessage, ElLoading } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { useRouter, useRoute } from 'vue-router'
import * as LoginApi from '@/api/login'
import * as authUtil from '@/utils/auth'
import { usePermissionStore } from '@/store/modules/permission'
import { useLocale } from '@/hooks/web/useLocale'

const { t, locale } = useI18n()
const router = useRouter()
const route = useRoute()
const loading = ref(false)
const step = ref(1)
const loginLoading = ref(false)

const form = ref({
  username: '',
  password: '',
  rememberMe: false,
  code: '',
  uuid: ''
})

// 邮箱后缀列表
const domainList = [
  { value: '@rhythmicsoar.com', label: '@rhythmicsoar.com', shortLabel: '@rhythmicsoar.com' },
  { value: '@ziyouqingchun.com', label: '@ziyouqingchun.com', shortLabel: '@ziyouqingchun.com' },
  { value: '@ulianghui.com', label: '@ulianghui.com', shortLabel: '@ulianghui.com' }
]
const selectedDomain = ref(domainList[0].value)

// 获取路由参数中的 redirect
const redirect = ref(route.query.redirect as string)
const permissionStore = usePermissionStore()

// 处理下一步
const handleNext = () => {
  if (!form.value.username) {
    ElMessage.warning(t('login.usernamePlaceholder'))
    return
  }
  // 保存完整邮箱地址
  const fullUsername = form.value.username + selectedDomain.value
  form.value.username = fullUsername
  step.value = 2
}

// 返回修改账号
const handleChangeAccount = () => {
  form.value.username = form.value.username.split('@')[0]
  step.value = 1
}

const { changeLocale } = useLocale()

const handleLanguageChange = async (lang: string) => {
  await changeLocale(lang)
}

// 修改登录方法
const handleLogin = async () => {
  if (!form.value.password) {
    ElMessage.warning(t('login.passwordPlaceholder'))
    return
  }
  
  loginLoading.value = true
  try {
    // 验证表单
    const data = await validForm()
    if (!data) {
      return
    }

    // 调用登录接口
    const res = await LoginApi.login({
      username: form.value.username,
      password: form.value.password,
      captchaVerification: ''
    })
    
    if (!res) {
      return
    }

    // 显示加载中
    const loading = ElLoading.service({
      lock: true,
      text: '正在加载系统...',
      background: 'rgba(0, 0, 0, 0.7)'
    })

    try {
      // 处理记住我
      if (form.value.rememberMe) {
        authUtil.setLoginForm(form.value)
      } else {
        authUtil.removeLoginForm()
      }

      // 保存 token
      authUtil.setToken(res)

      // 处理重定向
      if (!redirect.value) {
        redirect.value = '/'
      }

      // 判断是否为 SSO 登录
      if (redirect.value.indexOf('sso') !== -1) {
        window.location.href = window.location.href.replace('/login?redirect=', '') 
      } else {
        router.push({ path: redirect.value || permissionStore.addRouters[0].path })
      }
    } finally {
      loading.close()
    }
  } finally {
    loginLoading.value = false
  }
}

// 表单验证方法
const validForm = async () => {
  try {
    // 这里可以添加表单验证逻辑
    return true
  } catch (error) {
    return false
  }
}

const showFullDomain = ref()
// 点击关闭下拉框
onMounted(() => {
  document.addEventListener('click', (e: MouseEvent) => {
    const target = e.target as HTMLElement
    if (!target.closest('.domain-select') && !target.closest('.domain-dropdown')) {
      showFullDomain.value = false
    }
  })
  document.body.style.overflow = 'hidden'
})

onUnmounted(() => {
  document.body.style.overflow = ''
})
</script>

<style lang="scss" scoped>


// 响应式设计
@media screen and (width <= 1200px) {
  .right-section {
    padding: 40px 60px;
  }
}

@media screen and (width <= 768px) {
  .login-container {
    flex-direction: column;
  }

  .left-section {
    width: 100%;
    min-height: 200px;
    padding: 20px;

    .title {
      margin-top: 60px;
      font-size: 24px;
    }

    .subtitle {
      margin-top: 8px;
      font-size: 14px;
    }
  }

  .right-section {
    width: 100%;
    padding: 20px;
  }

  .login-form {
    padding: 50px 0;
  }

  .other-login {
    margin-top: 40px;
  }

  .copyright {
    flex-direction: column;
    gap: 4px;
    padding: 200px 0;
  }
}

// 平板尺寸
@media screen and (width >= 769px) and (width <= 1024px) {
  .left-section {
    padding: 30px;
  }

  .right-section {
    padding: 30px;
  }

  .login-form {
    max-width: 340px;
  }
}

// 小屏笔记本
@media screen and (height <= 700px) {
  .title {
    margin-top: 80px;
  }

  .login-form {
    padding: 20px 0;
  }

  .other-login {
    margin-top: 40px;
  }
}

// 小屏幕
@media screen and (width <= 320px) {
  .login-form {
    .input-group input {
      font-size: 13px;
    }

    .domain-select {
      font-size: 13px;
    }
  }

  .other-login .login-methods {
    gap: 30px;
  }
}

// 横屏模式
@media screen and (orientation: landscape) and (height <= 500px) {
  .login-container {
    position: absolute;
    min-height: 500px;
  }

  .main-section {
    height: auto;
    min-height: 500px;
  }

  .left-section {
    padding: 20px;

    .title {
      margin-top: 40px;
    }
  }

  .login-form {
    padding: 10px 0;
  }
}

// 响应式调整
@media (width <= 768px) {
  .lang-switch {
    top: 20px;
    right: 20px;
  }

  .input-wrapper {
    input {
      height: 44px; // 在移动端增加输入框高度
    }
  }

  .next-btn {
    height: 44px; // 在移动端增加按钮高度
  }

  .other-login {
    margin-top: 40px;
  }
}

// 响应式调整
@media (width <= 768px) {
  .other-login {
    margin-top: 32px;
    
    .login-methods {
      gap: 40px;
    }
  }
}

.login-container {
  position: fixed;
  top: 0;
  left: 0;
  display: flex;
  width: 100%;
  min-height: 100vh;
  overflow-y: auto;
  background: #fff;
  flex-direction: row;
  -webkit-overflow-scrolling: touch;
  
  @media (width <= 1200px) {
    flex-direction: column;
  }
}

.left-section {
  position: relative;
  width: 40%;
  min-height: 100vh;
  padding: 40px 64px;
  color: white;
  background: url('@/assets/left.png') no-repeat center center;
  background-size: cover;

  @media (width <= 1200px) {
    display: none;
  }

  .logo-wrapper {
    display: flex;
    align-items: center;
    gap: 12px;

    .logo {
      width: 40px;
      height: 40px;
    }

    span {
      font-size: 28px;
      font-weight: 500;
      color: #fff;
    }
  }

  .title {
    margin-top: 250px;
    font-size: 32px;
    font-weight: 600;
  }

  .subtitle {
    margin-top: 12px;
    font-size: 18px;
    font-weight: 500;
    opacity: 0.8;
  }
}

// 移动端顶部
.mobile-header {
  display: none;
  padding: 48px 20px 32px;
  text-align: center;
  background: #fff;

  @media (width <= 1200px) {
    display: block;
  }

  .logo-wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    margin-bottom: 12px;

    .logo {
      width: 200px;
      height: 50px;
    }

    .brand-name {
      font-size: 20px;
      font-weight: 500;
      color: #1D2129;
    }
  }

  .subtitle {
    margin-top: 4px;
    font-size: 14px;
    color: #86909C;
  }
}

.main-section {
  position: relative;
  display: flex;
  height: 100vh;
  padding: 40px;
  overflow-y: auto;
  flex: 1;
  flex-direction: column;

  @media (width <= 1200px) {
    height: auto;
    min-height: 100vh;
    padding-top: 0;
  }

  @media (width <= 768px) {
    padding: 80px 20px 20px;
  }
}

.login-form {
  display: flex;
  width: 100%;
  max-width: 400px;
  padding: 40px 0;
  margin: 0 auto;
  flex: 1;
  flex-direction: column;
  justify-content: center;

  @media (width <= 768px) {
    justify-content: flex-start;
    padding-top: 20px;
  }
}

.form-title {
  margin-bottom: 32px;
  font-size: 24px;
  font-weight: 500;
  color: #1D2129;
}

.input-group {
  margin-bottom: 24px;

  .input-wrapper {
    position: relative;
    display: flex;
    overflow: hidden;
    background: #fff;
    border: 1px solid #E5E6EB;
    border-radius: 6px;
    transition: all 0.3s;
    align-items: center;

    &:focus-within {
      border-color: #165DFF;
      box-shadow: 0 0 0 2px rgb(22 93 255 / 10%);
    }

    input {
      height: 38px;
      padding: 0 12px;
      font-size: 14px;
      color: #1D2129;
      border: none;
      outline: none;
      flex: 1;

      &::placeholder {
        color: #86909C;
      }
    }

    .domain-text {
      position: absolute;
      right: 12px;
      display: flex;
      font-size: 14px;
      color: #1D2129;
      pointer-events: none;
      align-items: center;
      gap: 4px;

      .select-icon {
        font-size: 12px;
        color: #86909C;
      }
    }

    :deep(.domain-select) {
      position: absolute;
      right: 0;
      width: 140px;
      opacity: 0;

      .el-input__wrapper {
        height: 38px;
        background: none;
        box-shadow: none !important;
      }

      .el-input__inner {
        opacity: 0;
      }

      .el-select__caret {
        display: none;
      }
    }
  }
}

.user-info {
  display: flex;
  padding: 12px 16px;
  margin-bottom: 20px;
  background: #F2F3F5;
  border-radius: 6px;
  justify-content: space-between;
  align-items: center;

  span {
    font-size: 14px;
    color: #1D2129;
  }

  .change-btn {
    font-size: 14px;
    color: #165DFF;
    cursor: pointer;
    background: none;
    border: none;

    &:hover {
      opacity: 0.8;
    }
  }
}

.next-btn {
  width: 100%;
  height: 44px;
  margin-top: 24px;
  font-size: 16px;
  font-weight: 500;
  color: white;
  cursor: pointer;
  background: #4E5BA8;
  border: none;
  border-radius: 8px;
  transition: all 0.3s;

  &:hover {
    background: darken(#4E5BA8, 5%);
  }

  &:disabled {
    cursor: not-allowed;
    background: #E5E6EB;
  }
}

.other-login {
  margin-top: 48px;
  
  @media (width <= 1200px) {
    margin-top: 32px;
  }
  
  .divider {
    position: relative;
    margin-bottom: 32px;
    font-size: 13px;
    color: #86909C;
    text-align: center;

    &::before,
    &::after {
      position: absolute;
      top: 50%;
      width: 30%;
      height: 1px;
      background: #E5E6EB;
      content: '';
    }

    &::before { left: 0; }

    &::after { right: 0; }
  }

  .login-methods {
    display: flex;
    justify-content: center;
    gap: 64px;
    margin-top: 24px;

    .login-icon {
      display: flex;
      width: 48px;
      height: 48px;
      cursor: pointer;
      align-items: center;
      justify-content: center;
      border: 1px solid #E5E6EB;
      border-radius: 50%;
      transition: all 0.3s;

      &:hover {
        border-color: currentcolor;
        transform: translateY(-2px);
      }

      .icon-img {
        width: 24px;
        height: 24px;
        object-fit: contain;
      }
    }

    .weixin-icon {
      color: #07C160;
    }

    .feishu-icon {
      color: #3370FF;
    }

    .google-icon {
      color: #4285F4;
    }
  }
}

.copyright {
  padding: 16px;
  margin-top: auto;
  font-size: 12px;
  color: #999;
  text-align: center;

  @media (width <= 768px) {
    padding: 16px;
  }
  
  p {
    margin: 4px 0;
  }
}

.lang-switch {
  position: absolute;
  top: 20px;
  right: 32px;
  z-index: 10;
  
  .lang-dropdown-link {
    display: flex;
    padding: 6px 8px;
    font-size: 14px;
    color: #1D2129;
    cursor: pointer;
    border: 1px solid #E5E6EB;
    border-radius: 6px;
    transition: all 0.3s;
    align-items: center;
    gap: 8px;

    &:hover {
      color: #4E5BA8;
      border-color: #4E5BA8;
    }

    .language-icon {
      width: 16px;
      height: 16px;
    }
  }
}

:deep(.el-dropdown-menu__item) {
  display: flex;
  min-width: 120px;
  padding: 8px 16px;
  align-items: center;
  justify-content: space-between;

  .active {
    color: #4E5BA8;
  }

  .el-icon {
    margin-left: 8px;
    color: #4E5BA8;
  }
}

// 添加全局样式
:global(.domain-select-dropdown) {
  .el-select-dropdown__item {
    padding: 8px 16px;
    font-size: 14px;
    
    &.selected {
      font-weight: bold;
      color: #4E5BA8;
    }
    
    &:hover {
      background-color: #F5F6F7;
    }
  }
}

// 下拉菜单样式
:deep(.el-select-dropdown.el-popper) {
  .el-select-dropdown__item {
    height: 36px;
    padding: 8px 12px;
    font-size: 14px;
    line-height: 20px;
    color: #1D2129;
    
    &.selected {
      font-weight: 400;
      color: #165DFF;
      background-color: #F2F3F5;
    }
    
    &:hover {
      background-color: #F2F3F5;
    }

    .domain-option {
      display: block;
      font-size: 14px;
    }
  }
}

.back-btn {
  display: flex;
  margin-bottom: 24px;
  font-size: 14px;
  color: #1D2129;
  cursor: pointer;
  align-items: center;
  gap: 4px;

  &:hover {
    color: #165DFF;
  }
}

.password-title {
  margin-bottom: 8px;
  font-size: 24px;
  font-weight: 500;
  color: #1D2129;
}

.account-info {
  margin-bottom: 32px;
  font-size: 14px;
  color: #86909C;
}

.input-wrapper {
  position: relative;
  width: 100%;

  input {
    width: 100%;
    height: 40px;
    padding: 0 140px 0 12px;
    font-size: 14px;
    border: 1px solid #E5E6EB;
    border-radius: 6px;
    
    &:focus {
      border-color: #165DFF;
      outline: none;
    }
  }

  .domain-select-wrapper {
    position: absolute;
    top: 1px;
    right: 1px;
    bottom: 1px;
    width: 140px;

    .domain-select {
      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      width: 100%;
      cursor: pointer;
      opacity: 0;

      :deep(.el-input__wrapper) {
        cursor: pointer;
        background: transparent;
        box-shadow: none !important;
      }

      :deep(.el-input__inner) {
        cursor: pointer;
        opacity: 0;
      }

      :deep(.el-input) {
        cursor: pointer;
      }
    }

    .domain-text {
      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      display: flex;
      padding: 0 24px 0 12px;
      font-size: 14px;
      color: #1D2129;
      pointer-events: none;
      background: #F7F8FA;
      border-left: 1px solid #E5E6EB;
      border-radius: 0 6px 6px 0;
      align-items: center;
      
      .select-icon {
        position: absolute;
        right: 8px;
        font-size: 12px;
        color: #86909C;
      }
    }
  }
}

.forgot-password {
  margin-top: 16px;
  text-align: right;

  a {
    font-size: 14px;
    color: #165DFF;
    text-decoration: none;

    &:hover {
      opacity: 0.8;
    }
  }
}

// 下拉菜单样式
:deep(.domain-select-dropdown) {
  .el-select-dropdown__item {
    display: flex !important;
    height: 36px;
    padding: 8px 12px;
    font-size: 14px;
    line-height: 20px;
    color: #1D2129;
    cursor: pointer;
    align-items: center;
    justify-content: space-between;

    &.selected, &.is-selected {
      color: #165DFF;
      background-color: #F2F3F5;
    }

    &:hover {
      background-color: #F2F3F5;
    }

    .domain-option {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
    }

    .el-icon {
      font-size: 14px;
      color: #165DFF;
    }
  }
}
</style>